import requests
import time


def get_audio_url(track_id):
    api_url = "https://www.ximalaya.com/revision/play/v1/audio"
    params = {
        "id": track_id,
        "ptype": "1",
        "device": "web",
        "network": "wifi"
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        "Referer": f"https://www.ximalaya.com/sound/{track_id}",
        "Accept": "application/json, text/plain, */*",
        "Cookie": "xm_xxxx=你的实际Cookie",  # 必须项
        "X-Requested-With": "XMLHttpRequest"
    }

    try:
        response = requests.get(api_url, headers=headers, params=params, timeout=10)
        print(f"调试信息：状态码 {response.status_code}，响应长度 {len(response.text)}")

        if response.status_code != 200:
            print(f"错误响应内容：{response.text[:500]}")
            return None

        data = response.json()
        return data['data']['src']

    except Exception as e:
        print(f"完整错误追踪：{str(e)}")
        return None


# 使用示例
if __name__ == "__main__":
    track_id = "772371506"
    audio_url = get_audio_url(track_id)

    if audio_url:
        print("成功获取地址：", audio_url)
        # 调用下载函数
    else:
        print("⚠️ 请按以下步骤操作：")
        print("1. 通过浏览器访问页面手动获取Cookie")
        print("2. 确认音频不是付费内容")
        print("3. 检查网络是否正常")